const express = require('express');
const router = express.Router();
const orderManagementService = require('../../services/orderManagementService');
const auth = require('../../middleware/auth');
const userAdminAuth = require('../../middleware/userAdminAuth');

/**
 * 获取订单列表
 */
router.get('/', auth, userAdminAuth, async (req, res) => {
  try {
    const {
      page = 1,
      limit = 20,
      search,
      status,
      paymentStatus,
      paymentMethod,
      userId,
      startDate,
      endDate,
      sortBy = 'createdAt',
      sortOrder = 'DESC'
    } = req.query;

    const result = await orderManagementService.getOrderList({
      page: parseInt(page),
      limit: parseInt(limit),
      search,
      status,
      paymentStatus,
      paymentMethod,
      userId: userId ? parseInt(userId) : undefined,
      startDate,
      endDate,
      sortBy,
      sortOrder
    });

    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取订单列表失败',
      error: error.message
    });
  }
});

/**
 * 获取订单详情
 */
router.get('/:id', auth, userAdminAuth, async (req, res) => {
  try {
    const orderId = parseInt(req.params.id);
    const result = await orderManagementService.getOrderById(orderId);

    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(404).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 更新订单状态
 */
router.put('/:id/status', auth, userAdminAuth, async (req, res) => {
  try {
    const orderId = parseInt(req.params.id);
    const { status, notes } = req.body;

    if (!status) {
      return res.status(400).json({
        success: false,
        message: '订单状态不能为空'
      });
    }

    await orderManagementService.updateOrderStatus(orderId, status, req.user.id, notes);

    res.json({
      success: true,
      message: '订单状态更新成功'
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 处理订单退款
 */
router.post('/:id/refund', auth, userAdminAuth, async (req, res) => {
  try {
    const orderId = parseInt(req.params.id);
    const { refundAmount, refundReason } = req.body;

    if (!refundAmount || refundAmount <= 0) {
      return res.status(400).json({
        success: false,
        message: '退款金额必须大于0'
      });
    }

    if (!refundReason) {
      return res.status(400).json({
        success: false,
        message: '退款原因不能为空'
      });
    }

    await orderManagementService.processRefund(orderId, refundAmount, refundReason, req.user.id);

    res.json({
      success: true,
      message: '退款处理成功'
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 批量更新订单
 */
router.put('/batch', auth, userAdminAuth, async (req, res) => {
  try {
    const { orderIds, updateData } = req.body;

    if (!orderIds || !Array.isArray(orderIds) || orderIds.length === 0) {
      return res.status(400).json({
        success: false,
        message: '订单ID列表不能为空'
      });
    }

    await orderManagementService.batchUpdateOrders(orderIds, updateData, req.user.id);

    res.json({
      success: true,
      message: `成功更新 ${orderIds.length} 个订单`
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 获取订单概览统计
 */
router.get('/analytics/overview', auth, userAdminAuth, async (req, res) => {
  try {
    const { days = 30 } = req.query;
    const overview = await orderManagementService.getOrderOverview(parseInt(days));

    res.json({
      success: true,
      data: overview
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取订单概览失败',
      error: error.message
    });
  }
});

/**
 * 获取订单趋势统计
 */
router.get('/analytics/trends', auth, userAdminAuth, async (req, res) => {
  try {
    const { days = 30 } = req.query;
    const trends = await orderManagementService.getOrderTrends(parseInt(days));

    res.json({
      success: true,
      data: trends
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取订单趋势失败',
      error: error.message
    });
  }
});

/**
 * 获取异常订单
 */
router.get('/analytics/abnormal', auth, userAdminAuth, async (req, res) => {
  try {
    const abnormalOrders = await orderManagementService.getAbnormalOrders();

    res.json({
      success: true,
      data: abnormalOrders
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取异常订单失败',
      error: error.message
    });
  }
});

/**
 * 导出订单数据
 */
router.get('/export/excel', auth, userAdminAuth, async (req, res) => {
  try {
    const {
      search,
      status,
      paymentStatus,
      startDate,
      endDate
    } = req.query;

    const exportData = await orderManagementService.exportOrders({
      search,
      status,
      paymentStatus,
      startDate,
      endDate
    });

    // 设置响应头
    res.setHeader('Content-Type', 'application/json');
    res.setHeader('Content-Disposition', 'attachment; filename=orders.json');

    res.json({
      success: true,
      data: exportData,
      message: `导出 ${exportData.length} 条订单数据`
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '导出订单数据失败',
      error: error.message
    });
  }
});

module.exports = router